package com.banmao.mall.service.client.impl;

import com.banmao.mall.mapper.CollectMapper;
import com.banmao.mall.model.bo.client.collect.AddorDeleteBO;
import com.banmao.mall.model.bo.client.collect.CollectListBO;
import com.banmao.mall.model.vo.client.collect.AddorDeleteVO;
import com.banmao.mall.model.vo.client.collect.CollectListVO;
import com.banmao.mall.model.vo.client.collect.CollectVO;
import com.banmao.mall.service.client.CollectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class CollectServiceImpl implements CollectService {

    @Autowired
    CollectMapper collectMapper;

    @Override
    public CollectListVO collectList(CollectListBO collectListBO) {

        PageHelper.startPage(collectListBO.getPage(), collectListBO.getSize());

        List<CollectVO> collectVOS = collectMapper.selectGoodsByUserID(collectListBO);

        PageInfo<CollectVO> collectVOPageInfo = new PageInfo<>(collectVOS);
        int totalPages = collectVOPageInfo.getPages();

        // 封装结果
        CollectListVO collectListVO = new CollectListVO();
        collectListVO.setTotalPages(totalPages);
        collectListVO.setCollectList(collectVOS);

        return collectListVO;
    }

    @Override
    public AddorDeleteVO collectAddorDelete(AddorDeleteBO addorDeleteBO) {

        // 先查找collect表中当前用户有没有收藏该商品的记录
        Boolean deleted = collectMapper.selectExistDeleted(addorDeleteBO);

        System.out.println(deleted);
        if(deleted != null) {
            // 当deleted不为null时表示记录存在，只需要将该记录deleted更新一下
            // 将相反的deleted状态存入BO对象
            addorDeleteBO.setDeleted(!deleted);
            int result = collectMapper.updateWithDeleted(addorDeleteBO);
            if(result == 0) {
                throw new RuntimeException("SQL错误！");
            }

        } else {
            // 当deleted为null时表示记录不存在，需要添加操作
            int result = collectMapper.insertCollectByValueId(addorDeleteBO);
            if(result == 0) {
                throw new RuntimeException("SQL错误！");
            }
        }

        AddorDeleteVO addorDeleteVO = new AddorDeleteVO();
        // 通过deleted的值判断进行的是add操作还是delete操作
        if(deleted == null || deleted) {
            addorDeleteVO.setType("add");
            return addorDeleteVO;
        }

        addorDeleteVO.setType("delete");
        return addorDeleteVO;
    }


}
